using System;
using System.Collections.Generic;
using System.Configuration;
using System.Security.Permissions;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Core.BOL;
using Core.DAL;
using Core.Extentions;
using Core.Utils;
using ScoutNET.ActionsResults;
using ScoutNET.Attributes;

namespace ScoutNET.Controllers
{
    public class AlbumController : ApplicationController
    {
        private SectionRepository sr = new SectionRepository();
        private AlbumsRepository ar = new AlbumsRepository();
        private ImagesRepository ir = new ImagesRepository();
        private NewsRepository nr = new NewsRepository();
        private MailToGenerateRepository mtgr = new MailToGenerateRepository();
        
        #region Views
        [AuthorizeView(ErrorMessageKey = "Galerie_Index_Error_Acces", ShowToCrawler = true)]
        public ActionResult Index(string systemName, int id, int? page)
        {  
            tSite_Photos_Album album = ar.GetAlbumByID(id);
            string section = sr.GetSectionNameBySystemName(systemName);
            ViewData["PageTitle"] = Resources.Album_Index_Title.Replace("[SECTION]", section).Replace("[ALBUM_TITLE]", album.Title);
            ViewData["PageDescription"] = album.Title;
            ViewData["MetaThumbnail"] = ConfigurationManager.AppSettings["SiteUrl"] + Url.Action("MetaThumbnail", new { controller = "Photo", title = album.Title.ParseUrl(), id = album.DefaultImage.ToString() }) + ".jpg";
            ViewData["MetaTitle"] = album.Title;
            ViewData["AlbumTitle"] = album.Title;

            ViewData["SystemName"] = systemName;
            ViewData["UserType"] = UsersRepository.GetUserType(systemName);

            string[] saBreadcrumb = new String[3];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Galerie_Index_Breadcrumb.Replace("[SECTION]", section.ToLower()), "SectionIndex", "Index", "Galerie", null, null);
            saBreadcrumb[2] = album.Title;
            ViewData["Breadcrumb"] = saBreadcrumb;

            int itemPage = 9;
            double totalItems = Convert.ToDouble(ir.GetCountImagesByAlbum(id));
            int totalPages = (int)Math.Ceiling(totalItems / itemPage);
            int pageID = (page == null || page == 0) ? 1 : (int)page;
            pageID = (page > totalPages) ? totalPages : pageID;
            int skipItem = (pageID - 1) * itemPage;
            List<tSite_Photos_Image> lImages = ir.GetImagesByAlbumID(id, skipItem, itemPage);

            ViewData["SkipItems"] = skipItem;
            ViewData["TitleAlbum"] = album.Title;
            ViewData["TotalPages"] = totalPages;
            ViewData["TotalItems"] = lImages.Count;
            ViewData["Page"] = pageID;
            ViewData["AlbumID"] = id;

            return View(lImages);
        }

        [Authorize(Roles = "Animateur,C.U")]
        public ActionResult Create(int id, string systemName)
        {
            // Meta Tag
            string section = sr.GetSectionNameBySystemName(systemName).ToLower();
            ViewData["PageTitle"] = Resources.Galerie_Create_Title.Replace("[SECTION]", section);
            ViewData["PageDescription"] = Resources.Galerie_Create_Description.Replace("[SECTION]", section);

            ViewData["SystemName"] = systemName;
            ViewData["UserType"] = UsersRepository.GetUserType(systemName);

            //Breadcrumb
            tSite_Photos_Album album = ar.GetAlbumByID(id);
            string[] saBreadcrumb = new String[4];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Galerie_Index_Breadcrumb.Replace("[SECTION]", section), "SectionIndex", "Index", "Galerie", null, null);
            saBreadcrumb[2] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, album.Title, "SectionDetailsWithTitle", "Index", "Album", new RouteValueDictionary(new { systemName = systemName.UppercaseFirst(), ID = album.ID, Title = album.Title.ParseUrl() }), null);
            saBreadcrumb[3] = Resources.Album_Create_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            //Get data
            ViewData["AlbumID"] = id;
            ViewData["MaxRequestLength"] = Files.GetMaxRequestLength();
            ViewData["FormsToken"] = Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value;
            ViewData["Title"] = album.Title.ParseUrl();

            return View();
        }

        [Authorize(Roles = "Animateur,C.U")]
        public ActionResult Edit(int id, string systemName)
        {
            tSite_Photos_Album a = ar.GetAlbumByID(id);

            // Meta Tag
            string section = sr.GetSectionNameBySystemName(systemName).ToLower();
            ViewData["PageTitle"] = Resources.Album_Edit_Title.Replace("[ALBUMNAME]", a.Title);
            ViewData["PageDescription"] = Resources.Album_Edit_Description.Replace("[ALBUMNAME]", a.Title);

            ViewData["SystemName"] = systemName;
            ViewData["UserType"] = UsersRepository.GetUserType(systemName);

            //Breadcrumb
            string[] saBreadcrumb = new String[4];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Galerie_Index_Breadcrumb.Replace("[SECTION]", section), "SectionIndex", "Index", "Galerie", new RouteValueDictionary(new { systemName = systemName.UppercaseFirst() }), null);
            saBreadcrumb[2] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, a.Title, "SectionDetailsWithTitle", "Index", "Album", new RouteValueDictionary(new { systemName = systemName.UppercaseFirst(), ID = a.ID, Title = a.Title.ParseUrl() }), null);
            saBreadcrumb[3] = Resources.Album_Edit_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            //Get data
            ViewData["AlbumID"] = id;
            ViewData["MaxRequestLength"] = Files.GetMaxRequestLength();
            ViewData["FormsToken"] = Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value;

            return View();
        }

        [Authorize(Roles = "Animateur,C.U")]
        public ActionResult Delete(int ID)
        {
            ViewData["ID"] = ID.ToString();

            return View();
        }

        [HttpPost]
        [Authorize(Roles = "Animateur,C.U")]
        public EmptyResult Delete(FormCollection fc)
        {
            ar.DeleteAlbum(int.Parse(fc["ID"]));
            ar.Save();

            return new EmptyResult();
        }

        [Authorize(Roles = "Animateur,C.U")]
        public ActionResult Validation(int id, string systemName)
        {
            // Meta Tag
            tSite_Section section = sr.GetSectionsBySystemName(systemName);
            ViewData["PageTitle"] = Resources.Galerie_Create_Title.Replace("[SECTION]", section.Section.ToLower());
            ViewData["PageDescription"] = Resources.Galerie_Create_Description;

            ViewData["SystemName"] = systemName;
            ViewData["UserType"] = UsersRepository.GetUserType(systemName);

            //Breadcrumb
            tSite_Photos_Album album = ar.GetAlbumByID(id);
            string[] saBreadcrumb = new String[4];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Galerie_Index_Breadcrumb.Replace("[SECTION]", section.Section.ToLower()), "SectionIndex", "Index", "Galerie", new RouteValueDictionary(new { systemName = systemName.UppercaseFirst() }), null);
            saBreadcrumb[2] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, album.Title, "SectionDetailsWithTitle", "Index", "Album", new RouteValueDictionary(new { systemName = systemName.UppercaseFirst(), ID = album.ID, Title = album.Title.ParseUrl() }), null);
            saBreadcrumb[3] = Resources.Album_Validation_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            if (album != null)
            {
                if (album.NID == null)
                {
                    //Insert news
                    int resourceID = new Random().Next(1, 5);
                    string albumUrl = this.Url.Action("Index", new { controller = "Album", systemName = album.SystemName.UppercaseFirst(), id = album.ID, title = album.Title.ParseUrl() });// string.Concat("/", album.SystemName.UppercaseFirst() + "/Album/Index/", album.ID, "/", album.Title.ParseUrl());
                    string defaultImageUrl = string.Concat("/Album/MailImageResize/", album.Title.ParseUrl(), "/", album.DefaultImage.ToString(), ".jpg");

                    tSite_New n = new tSite_New();
                    n.InsertDate = DateTime.Now.GetNowTimeByTimeZone();
                    n.Title = Resources.Album_Validation_News_Title.Replace("[SECTION]", section.Sections.ToLower());
                    n.News = GetNews(resourceID).Replace("[ALBUM_TITLE]", album.Title).Replace("[SECTION]", section.Sections.ToLower()).Replace("[ALBUM_URL]", albumUrl).Replace("[THUMBNAIL_URL]", defaultImageUrl);
                    n.SID = album.SID;
                    nr.InsertNews(n);
                    nr.Save();

                    // Update album with the news ID
                    album.NID = n.ID;
                    ar.Save();

                    // Add user mail
                    tMail_ToGenerate tg = new tMail_ToGenerate();
                    tg.Action = this.ControllerContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
                    tg.ItemID = id;
                    tg.SID = n.SID;
                    tg.InsertDate = DateTime.Now.GetNowTimeByTimeZone();
                    tg.ResourceID = 1;
                    mtgr.InsertMail(tg);
                    mtgr.Save();

                }

                ViewData["ValidationMessage"] = Resources.Album_Validation_Message;

                return View();
            }
            else
            {
                return View("Error404");
            }
        }

        public UploadPicturesResult UploadImage(HttpPostedFileBase fileData, int ID, string token)
        {
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(token);
            if (ticket != null)
            {
                var identity = new FormsIdentity(ticket);
                if (identity.IsAuthenticated)
                {
                    tSite_Photos_Album album = ar.GetAlbumByID(ID);

                    tSite_Photos_Image image = new tSite_Photos_Image();
                    image.AID = album.ID;
                    image.SID = album.SID;
                    image.ImageName = Guid.NewGuid();
                    ir.InsertImage(image);
                    ir.Save();

                    string folder = ConfigurationManager.AppSettings["GalleryPath"] + ID.ToString("D6") + "/";
                    string imageName = image.ImageName.ToString() + ".jpg";

                    return new UploadPicturesResult(fileData, folder, imageName, ImageMode.GalleryPhoto, image.ID);
                }
            }
            return null;
        }

        [AuthorizeView(ShowToCrawler = true)]
        [OutputCache(CacheProfile="Photo")]
        [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
        public ActionResult ImageResize(int? ID, string title)
        {
            if (ID != null)
            {
                byte[] baImage = Imaging.GetResizedImage((int)ID, ImageMode.GalleryThumbnail, true);
                return new FileContentResult(baImage, "image/jpeg");
            }
            else
            {
                return View("Error404");
            }
        }

        [OutputCache(CacheProfile="Photo")]
        [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
        public ActionResult MailImageResize(int? ID, string title)
        {
            if (ID != null)
            {
                byte[] baImage = Imaging.GetResizedImage((int)ID, ImageMode.MailThumbnail, true, false);
                return new FileContentResult(baImage, "image/jpeg");
            }
            else
            {
                return View("Error404");
            }
        }

        [Authorize(Roles = "Animateur,C.U")]
        [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
        public FileResult RightRotationImage(int ID, string title)
        {
            tSite_Photos_Image img = ir.GetImageByID(ID);
            Dictionary<string, int> imageSize = Imaging.GetImageSize(ImageMode.GalleryThumbnail);
            string picturePath = ConfigurationManager.AppSettings["GalleryPath"] + img.AID.ToString("D6") + "/" + img.ImageName.ToString() + ".jpg";
            string serverPicturePath = HttpContext.Server.MapPath(picturePath);

            Imaging.DeleteImageCached(img.ID);

            byte[] baImage = Core.Utils.Files.FileToArray(serverPicturePath);
            baImage = Imaging.RightRotateImage90(baImage);
            Files.ByteArrayToFile(serverPicturePath, baImage);
            baImage = Imaging.ResizeImageToPortrait(baImage, imageSize["W"], imageSize["H"]);
            baImage = Imaging.Watermark(baImage, ConfigurationManager.AppSettings["Watermark"]);
            
            string path = Url.RouteUrl("ImageResizer", new {action = "ImageResize", controller = "Album", title = img.AlbumName.ParseUrl(), ID = img.ID});
            HttpResponse.RemoveOutputCacheItem(path);

            return new FileContentResult(baImage, "image/jpeg");
        }

        [Authorize(Roles = "Animateur,C.U")]
        [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
        public FileResult LeftRotationImage(int ID, string title)
        {
            tSite_Photos_Image img = ir.GetImageByID(ID);
            Dictionary<string, int> imageSize = Imaging.GetImageSize(ImageMode.GalleryThumbnail);
            string picturePath = ConfigurationManager.AppSettings["GalleryPath"] + img.AID.ToString("D6") + "/" + img.ImageName.ToString() + ".jpg";
            string serverPicturePath = HttpContext.Server.MapPath(picturePath);

            Imaging.DeleteImageCached(img.ID);

            byte[] baImage = Core.Utils.Files.FileToArray(serverPicturePath);
            baImage = Imaging.LeftRotateImage90(baImage);
            Files.ByteArrayToFile(serverPicturePath, baImage);
            baImage = Imaging.ResizeImageToPortrait(baImage, imageSize["W"], imageSize["H"]);
            baImage = Imaging.Watermark(baImage, ConfigurationManager.AppSettings["Watermark"]);

            string path = Url.RouteUrl("ImageResizer", new { action = "ImageResize", controller = "Album", title = img.AlbumName.ParseUrl(), ID = img.ID });
            HttpResponse.RemoveOutputCacheItem(path);

            return new FileContentResult(baImage, "image/jpeg");
        }

        [HttpPost]
        [Authorize(Roles = "Animateur,C.U")]
        [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
        public EmptyResult DefaultPicture(int ID, string title, FormCollection fc)
        {
            tSite_Photos_Album a = ar.GetAlbumByID(int.Parse(fc["AID"]));
            a.DefaultImage = ID;
            ar.Save();
            return new EmptyResult();
        }

        [Authorize]
        public ActionResult ZipFile(int ID, string systemName)
        {
            tSite_Photos_Album a = ar.GetAlbumByID(ID);
            a.StatDownload = a.StatDownload + 1;
            ar.Save();

            MembershipUser mu = Membership.GetUser();

            if (mu != null && a != null)
            {
                string[] parametres = new string[2];
                parametres[0] = a.ID.ToString();
                parametres[1] = ((Guid)mu.ProviderUserKey).ToString();

                KeyValuePair<TaskManagerAction, object> taskParametres = new KeyValuePair<TaskManagerAction, object>(TaskManagerAction.ZipAlbum, parametres);
                TaskManager.AddTask(taskParametres);

                return View();
            }
            else
            {
                return View("Error404");
            }
        }
        #endregion

        #region Private Methodes
        public string GetNews(int resourceID)
        {
            switch (resourceID)
            {
                case 1:
                    return Resources.Album_Validation_News1;
                case 2:
                    return Resources.Album_Validation_News2;
                default:
                    return Resources.Album_Validation_News3;
            }
        }
        #endregion
    }
}
